package com.ypf.survey.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.ypf.survey.service.QuestionService;
import com.ypf.survey.service.UserService;
import com.ypf.survey.service.dto.AnswerDto;
import com.ypf.survey.service.dto.OptionDto;
import com.ypf.survey.service.dto.QuestionDto;
import com.ypf.survey.service.dto.UserDto;

@Controller
public class SurveyController {

	@Autowired
	private QuestionService questionService;
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/survey/{code}")
    public String welcome(@PathVariable String code, Model model) {
		Gson gson = new Gson();
		List<QuestionDto> questions = questionService.getQuestions();
		UserDto user = userService.getByCode(code);
		
		boolean hasAnswered = false;
		if(user != null){
			hasAnswered = userService.userHasAnswered(user.getId());
		}
		
		model.addAttribute("questions", gson.toJson(questions));
		model.addAttribute("user", gson.toJson(user));
		model.addAttribute("userNotFound", user == null);
		model.addAttribute("hasAnswered", hasAnswered);
		return "survey";
    }
	
	@RequestMapping(value="/report")
	public String report(Model model){
		Gson gson =  new Gson();
		List<AnswerDto> answers = questionService.getAnswers();
		List<OptionDto> options = questionService.getOptions();
		model.addAttribute("answers", gson.toJson(answers));
		model.addAttribute("options", gson.toJson(options));
		return "report";
	}
	
	@RequestMapping(value="/survey/answer", method = RequestMethod.POST)
	private @ResponseBody void answer(@RequestParam("id") int[] optionIds, Long userId, Model model){
		userService.userAnswer(optionIds, userId);
	}
}
